package net.dgg.zz.production.suspend.controller;

import com.alibaba.fastjson.JSONArray;
import net.dgg.framework.tac.utils.bean.DggRestResponse;
import net.dgg.framework.tac.utils.exception.DggBaseException;
import net.dgg.iboss.base.util.CustomerNumberEncryptionUtil;
import net.dgg.iboss.base.util.DesUtil;
import net.dgg.iboss.base.util.datatable.DataTableUtils;
import net.dgg.iboss.base.util.datatable.domain.DataTableRequest;
import net.dgg.iboss.base.util.datatable.domain.DataTableResponse;
import net.dgg.tmd.foundation.platform.annotation.AuthOpt;
import net.dgg.tmd.foundation.platform.common.util.TranslateUtil;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.zz.common.service.CommonMangerExtService;
import net.dgg.zz.common.utils.OrderHandleUtils;
import net.dgg.zz.flownode.dao.ZzProductNodeDao;
import net.dgg.zz.flownode.dao.ZzProductNodeFlowDao;
import net.dgg.zz.production.abnormal.controller.ZzBaseController;
import net.dgg.zz.production.excption.ProductOrderExcption;
import net.dgg.zz.production.inProcess.entity.ProductNode;
import net.dgg.zz.production.inProcess.entity.ProductNodeFlow;
import net.dgg.zz.production.suspend.service.ZzSubOrderService;
import net.dgg.zz.production.suspend.service.ZzSuspendedOrderService;
import net.fblock.log.NLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>@Title 暂缓订单列表</p>
 * <p>@Description </p>
 * <p>@Version 1.0.0 版本号</p>
 * <p>@author 孙上峰</p>
 * <p>@date 2018年08月15日</p>
 * <p>Copyright © dgg group.All Rights Reserved. 版权信息</p>
 */
@Controller
@RequestMapping("/zzsc/suspended_order")
public class ZzSuspendedOrderController extends ZzBaseController {
    @Autowired
    private ZzSuspendedOrderService zzSuspendedOrderService;
    @Autowired
    private ZzSubOrderService zzSubOrderService;
    @Autowired
    private SessionManager sessionManager;
    @Resource
    private DesUtil desUtil;
    @Resource
    private TranslateUtil translateUtil;
    @Autowired
    private CommonMangerExtService zzCommonMangerExtService;
    @Autowired
    private ZzProductNodeFlowDao zzProductNodeFlowDao;
    @Autowired
    private ZzProductNodeDao zzProductNodeDao;

    /**
     * 跳转到暂缓订单列表页
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String toMySuspendedOrderPage(Model model) {
        List<ProductNode> listNode = new ArrayList<>();
        //查询出当前登陆人的事业部id
        Map orgMap = zzCommonMangerExtService.findBusDeptById(sessionManager.getCurrentUser().getOrgId());
        if (orgMap != null && orgMap.size() != 0) {
            Map map = new HashMap();
            Map mapNode = new HashMap();
            StringBuilder ids = new StringBuilder();
            //根据事业部的id查询出改事业部配置流程节点ids
            map.put("deptIds", orgMap.get("id"));
            if (null == map.get("orderColumn")) {
                map.put("orderDir", "desc");
                map.put("orderColumn", "updateTime");
            }
            List<ProductNodeFlow> productNodeFlowList = zzProductNodeFlowDao.query(map);
            if (productNodeFlowList.size() > 0) {
                for (ProductNodeFlow productNodeFlow : productNodeFlowList) {
                    if (ids.length() > 0) {//该步即不会第一位有逗号，也防止最后一位拼接逗号！
                        ids.append(",");
                    }
                    ids.append(productNodeFlow.getId());
                }
                mapNode.put("deptIds", orgMap.get("id"));
                mapNode.put("processId", ids.toString().split(","));
                listNode = zzProductNodeDao.queryByFlowProcessIds(mapNode);
            }
        }
        model.addAttribute("listNode", listNode);
        return "zzsc/suspend/page_order_suspended";
    }

    /**
     * 查询暂缓订单列表数据
     */
    @RequestMapping("/query")
    @ResponseBody
    public DataTableResponse querySuspendedOrder(@RequestParam Map params, HttpServletRequest request) {
        DataTableRequest r = DataTableUtils.getParam(request);
        params.put("start", r.getStart());//获取当前页
        params.put("limit", r.getLength());//获取每页条数
        Map fileMap = new HashMap();
        fileMap.put("suspendTime", "suspendTime");
        fileMap.put("expectOpenDate", "expectOpenDate");
        fileMap.put("lastRemarkTime", "lastRemarkTime");//最新备注时间
        OrderHandleUtils.getOrderCol(r, params, fileMap);
        List<Map> listPage = zzSuspendedOrderService.queryMap(params);
        Integer count = zzSuspendedOrderService.count(params);
        return new DataTableResponse(r.getDraw(), count, count, listPage, "");
    }

    /**
     * (生产暂停)恢复办理弹窗
     *
     * @param subOrderId 生产子订单id
     * @author 赵有文
     */
    @AuthOpt(code = "ZZSC_RESUME_SUSPEND")
    @RequestMapping("/layer_resume_suspend")
    public String toResumHandlingLayer(ModelMap modelMap, String subOrderId) {
        Map subOrder = zzSubOrderService.queryMapById(subOrderId);
        modelMap.addAttribute("subOrder", subOrder);
        return "zzsc/suspend/layer_resume_suspend";

    }

    /**
     * (生产暂停)数据移交弹窗
     *
     * @param
     * @author 龙博
     */
    @AuthOpt(code = "ZZSC_RESUME_SUSPEND")
    @RequestMapping("/hand_over_data")
    public String toHandOverLayer(Model model,@RequestParam(value = "ids[]",required = false) List<Long> ids ) {
        if(CollectionUtils.isEmpty(ids)){
            throw new ProductOrderExcption("未获取到订单id，请刷新页面重试");
        }
        if(ids.size() == 1){
            model.addAttribute("isShow",false);
            model.addAttribute("orderList",zzSubOrderService.getCheckCloseAuditOrder(ids));
        }else {
            model.addAttribute("isShow",true);
            model.addAttribute("orderList",zzSubOrderService.getCheckCloseAuditOrder(ids));
        }
        return "zzsc/suspend/hand_over_data";

    }


    /**
     * @Author Bo Long
     * @Description //TODO 修改流程人员弹窗
     * @Date 2020-11-5 16:10:38
     * @Param
     * @return
     **/
    @AuthOpt(code = "ZZSC_RESUME_SUSPEND")
    @RequestMapping("/modify_order_dialog.html")
    public String modifyOrderDialog(Model model,@RequestParam(value = "ids[]",required = false) List<Long> ids){
        if(CollectionUtils.isEmpty(ids)){
            throw new ProductOrderExcption("未获取到订单id，请刷新页面重试");
        }
        if(ids.size() == 1){
            model.addAttribute("isShow",false);
            model.addAttribute("orderList",zzSubOrderService.getCheckCloseAuditOrder(ids));
        }else {
            model.addAttribute("isShow",true);
            model.addAttribute("orderList",zzSubOrderService.getCheckCloseAuditOrder(ids));
        }
            return "zzsc/suspend/modify_order_dialog";
    }







    /**
     * （生产暂停）恢复办理
     *
     * @param para
     * @return
     */
    @NLog
    @RequestMapping("/resume_suspend")
    @ResponseBody
    public DggRestResponse doResumeSuspend(@RequestParam Map para) {

        try {
            zzSuspendedOrderService.resumeAndRemark(para);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse("恢复失败！");
        }
        return this.getSuccessResponse("");
    }

    /**
     * 判断是否是协单人员
     * @param id
     * @return
     */
    @NLog
    @RequestMapping("/isDo")
    @ResponseBody
    public DggRestResponse isDo(@RequestParam Long id) {
        boolean state =  zzSuspendedOrderService.isDo(id);
        if(state){
            return this.getSuccessResponse("");
        }else{
            return this.getFailResponse("协单人员不能恢复办理！");
        }

    }


    /**
    * <p>@Description 跳转到团队生产暂停页面</p>
    * <p>@author mqy</p>
    * <p>@Time 2018/9/28 0028 15:28 创建时间</p>
    * <p>@return</p>
    */
    @NLog
    @RequestMapping(value = "/team_page_order_suspended")
    public String teamSuspendOrderPage(Model model) {
        List<ProductNode> listNode = new ArrayList<>();
        //查询出当前登陆人的事业部id
        Map orgMap = zzCommonMangerExtService.findBusDeptById(sessionManager.getCurrentUser().getOrgId());
        if (orgMap != null && orgMap.size() != 0) {
            Map map = new HashMap();
            Map mapNode = new HashMap();
            StringBuilder ids = new StringBuilder();
            //根据事业部的id查询出改事业部配置流程节点ids
            map.put("deptIds", orgMap.get("id"));
            if (null == map.get("orderColumn")) {
                map.put("orderDir", "desc");
                map.put("orderColumn", "updateTime");
            }
            List<ProductNodeFlow> productNodeFlowList = zzProductNodeFlowDao.query(map);
            if (productNodeFlowList.size() > 0) {
                for (ProductNodeFlow productNodeFlow : productNodeFlowList) {
                    if (ids.length() > 0) {//该步即不会第一位有逗号，也防止最后一位拼接逗号！
                        ids.append(",");
                    }
                    ids.append(productNodeFlow.getId());
                }
                mapNode.put("deptIds", orgMap.get("id"));
                mapNode.put("processId", ids.toString().split(","));
                listNode = zzProductNodeDao.queryByFlowProcessIds(mapNode);
            }
        }
        model.addAttribute("listNode", listNode);
        return "zzsc/team/team_page_order_suspended";
    }


    /**
    * <p>@Description 团队生产暂停页面数据</p>
    * <p>@author mqy</p>
    * <p>@Time 2018/9/28 0028 15:29 创建时间</p>
    * <p>@return</p>
    */
    @RequestMapping("/team_suspend_order_page_data")
    @ResponseBody
    @NLog
    public DataTableResponse teamSuspendOrderPageData(@RequestParam Map params, HttpServletRequest request) {
        DataTableRequest r = DataTableUtils.getParam(request);
        params.put("start", r.getStart());//获取当前页
        params.put("limit", r.getLength());//获取每页条数
        List<Map> listPage = zzSuspendedOrderService.teamSuspendOrderPageData(params);
        String[] transCols = new String[]{"originCode", "originType", "status", "abandonReason"};
        String[] encryptCols = new String[]{"customerPhone"};
        //翻译
        translateUtil.translateList(transCols, listPage);
        //解密
        listPage = desUtil.decryptListMap(encryptCols, listPage);
        //脱敏
        CustomerNumberEncryptionUtil.encryptionList(encryptCols, listPage);
        Integer count = zzSuspendedOrderService.count(params);
        return new DataTableResponse(r.getDraw(), count, count, listPage, "");
    }

}
